import email
import string, logging
from time import time
from flask import Blueprint, jsonify, request, session
from random import randint, sample

from models import User
from exts import db, redis_sever
from celery_tasks.send_mail_task import do_send_mail

bp = Blueprint("register", __name__, url_prefix="/register")

# 生成注册验证码
@bp.route("/captcha", methods=["POST", "GET"])
def do_captcha():
    # 获得前端发送来email，作为验证码的key
    try:
        email = request.get_json()["email"]
    except:
        return "get captcha fail", 400
    if not email:
        return "get captcha fail, no email", 400

    letters = string.ascii_letters + string.digits   
    captcha = "".join(sample(letters, 6))
    # 将验证码存入redis，5分钟将主动失效
    redis_sever.set(name=email, value=captcha.lower(), ex=5*600)
    # 验证码通过邮件发送给用户，采用celery并发这些长时间的io操作
    do_send_mail.delay(email, captcha) # 测试期间先注释掉，免得花费较多时间
    return "get captcha success"


# 用于生成随机用户账号，唯一数据库也不存在
# 9位
def rand_username():
    # 保证在数据库中都是唯一
    while True:
        # 系统自动生成账号
        username = str(randint(1, 9))
        for _ in range(8):
            username += str(randint(0, 9))
        user1 = User.query.filter(User.username == username).all()
        if len(user1) == 0:
            return username

@bp.route("/do", methods=["POST", "GET"])
def do_register():
    register_data = request.get_json()
    # register_data = {'email': '123@qq.com', 'password': '111', 'confirm': '111',
    #                     'nickname': '111', 'intro': '111', 'gender': '男', 'captcha': None, 'agreement': True}
    # 预防用户直接通过链接去访问
    if not register_data:
        return "请按系统的步骤, 正常去注册", 400
    # 检测邮箱是否注册过
    email_error = True if len(User.query.filter(User.email == register_data.get("email")).all()) != 0 else False
    if not email_error:
        # 先检验redis中是否有验证码，验证码不能为空，为空直接返回验证码错误给前端
        captcha = redis_sever.get(register_data["email"])
        if captcha == register_data["captcha"].lower() and captcha:
            # 验证正确，向数据库添加一条数据 && 生成一个用户账号，并返回给前端
            username = rand_username()
            user_info = User(
                nickname=register_data["nickname"],
                username = username,
                email = register_data["email"],
                password = register_data["password"],
                userintro = register_data["intro"] if register_data["intro"] else "ta是个神秘人",
                gender = register_data["gender"],
                createtime = int(time()),
                agree = "yes"
                )
            db.session.add(user_info)
            db.session.commit()
            print("已添加")
            return jsonify({"message":{"register_success": True, "username": username}})
        else:
            # 验证码错误
            return jsonify({"message": {"captcha_error": True}})
    else:
        return jsonify({"message":{"email_error": email_error}})